package comprehensive;

public class Exercises14 {
    // 1219、黄金矿工
    boolean[][] visit;
    int m;
    int n;
    int ret;

    public int getMaximumGold(int[][] grid) {
        m = grid.length;
        n = grid[0].length;
        visit = new boolean[m][n];

        for(int i = 0;i < m;i++) {
            for(int j = 0;j < n;j++) {
                // 以每一个数字开始位置，进行计算最大值
                if(grid[i][j] != 0) {
                    visit[i][j] = true;
                    dfs(grid,i,j,grid[i][j]);
                    visit[i][j] = false;
                }
            }
        }
        return ret;
    }

    int[] dx = {1,-1,0,0};
    int[] dy = {0,0,1,-1};

    public void dfs(int[][] grid,int i,int j,int path) {
        ret = Math.max(ret,path);

        for(int k = 0;k < 4;k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && !visit[x][y] && grid[x][y] != 0) {
                visit[x][y] = true;
                dfs(grid,x,y,path + grid[x][y]);
                visit[x][y] = false;
            }
        }
    }
}
